package io.xiaojl.xj2ee.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import io.xiaojl.xj2ee.common.exception.XjeeException;
import io.xiaojl.xj2ee.common.kit.PageWrapper;
import io.xiaojl.xj2ee.common.xss.SQLFilter;
import io.xiaojl.xj2ee.kit.JpaPageKit;
import io.xiaojl.xj2ee.modules.sys.entity.SysDeptEntity;
import io.xiaojl.xj2ee.modules.sys.entity.SysUserEntity;
import io.xiaojl.xj2ee.modules.sys.repository.SysUserRepository;
import io.xiaojl.xj2ee.modules.sys.service.SysUserService;


@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
	@Autowired
	private SysUserRepository sysUserRepository;
	@Autowired
	private SysDeptServiceImpl sysDeptService;
	
    @Override
    public PageWrapper<SysUserEntity> queryPage(Map<String, Object> params) {
    	PageWrapper<SysUserEntity> pageWrapper = new PageWrapper<SysUserEntity>(params);
		Page<SysUserEntity> page = sysUserRepository.findAll(JpaPageKit.getPageable(pageWrapper));
		List<SysUserEntity> list = page.getContent();
		for(SysUserEntity record: list){
			Long deptId = record.getDeptId();
			SysDeptEntity sysDeptEntity = sysDeptService.selectById(deptId);
			record.setDeptName(sysDeptEntity.getName());
		}
		pageWrapper.setList(list);
		pageWrapper.setTotalCount(Integer.parseInt(page.getTotalElements()+""));
		pageWrapper.setTotalPage(page.getTotalPages());
        return pageWrapper;
    }

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return sysUserRepository.queryAllMenuId(userId);
	}

	@Override
	public void save(SysUserEntity user) {
		sysUserRepository.save(user);
	}

	@Override
	public void update(SysUserEntity user) {
		sysUserRepository.saveAndFlush(user);
	}

	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
		SysUserEntity record = sysUserRepository.getOne(userId);
		if(record!=null){
			if(password.equals(record.getPassword())){
				record.setPassword(newPassword);
				sysUserRepository.saveAndFlush(record);
				return true;
			}else{
				throw new XjeeException("更新用户密码：用户ID["+userId+"]原密码不正确");
			}
		}else{
			throw new XjeeException("更新用户密码：用户ID["+userId+"]不存在");
		}
	}

	@Override
	public SysUserEntity selectById(Long userId) {
		return sysUserRepository.getOne(userId);
	}

	@Override
	public int deleteBatchIds(Long[] userIds) {
		List<SysUserEntity> list = sysUserRepository.findAllById(Arrays.asList(userIds));
		sysUserRepository.deleteAll(list);
		return list.size();
	}

	@Override
	public List<String> queryAllPerms(Long userId) {
		return sysUserRepository.queryAllPerms(userId);
	}

	@Override
	public SysUserEntity selectOne(SysUserEntity user) {
		Optional<SysUserEntity> optional = sysUserRepository.findOne(new Specification<SysUserEntity>() {
			/** serialVersionUID*/
			private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<SysUserEntity> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				if(StringUtils.isNotBlank(user.getEmail())){
					list.add(cb.like(root.get("email").as(String.class), "%"+SQLFilter.sqlInject(user.getEmail())+"%"));
				}
				if(StringUtils.isNotBlank(user.getUsername())){
					list.add(cb.like(root.get("username").as(String.class), "%"+SQLFilter.sqlInject(user.getUsername())+"%"));
				}
				if(StringUtils.isNotBlank(user.getMobile())){
					list.add(cb.like(root.get("mobile").as(String.class), "%"+SQLFilter.sqlInject(user.getMobile())+"%"));
				}
				
				Predicate[] ps = new Predicate[list.size()];
				query.where(list.toArray(ps));
				return null;
			}
		});
		
		return optional.get();
	}

}
